package com.qidian.common.beans;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import com.qidian.common.AccountType;
import com.qidian.common.TableMeta;

public class AccountBean implements ISyncBean
{
    Long accountId = -1L;
    String account ;
    AtomicInteger point = new AtomicInteger();
    AtomicInteger pointIncrement  = new AtomicInteger();
    AtomicInteger usedPoint = new AtomicInteger();
    AtomicInteger usedPointIncrement = new AtomicInteger() ;
    Long userId = -1L;
    long lastTime = 0 ;		// 最后一次使用时间
    long birthTime = 0L ;	// 创建时间
    long validTime = 0L ;	// 有效期(如果暂未使用,则为天数的毫秒数;否则为有效期的GMT毫秒数)
    long firstTime = 0L ;	// 第一次使用时间
    AtomicInteger sendCount = new AtomicInteger(0);
    AtomicInteger sendCountIncrement = new AtomicInteger(0);
    AtomicInteger reportCount = new AtomicInteger(0);
    AtomicInteger reportCountIncrement = new AtomicInteger(0) ;
    AtomicInteger status = new AtomicInteger(0);
    AtomicBoolean needSync = new AtomicBoolean(false) ;
    AccountType type = null ;
    
    public static final String clearSql = "delete from " + TableMeta.table_account +
    										" where " + TableMeta.column_status + " = -1 ";
	static long startTime = java.sql.Timestamp.valueOf("1970-01-01 00:00:00").getTime();
	
    
	public static AccountBean toAccountBean(ResultSet rs) throws SQLException 
	{
		AccountBean accountBean = new AccountBean() ;
		accountBean.setAccountId(rs.getLong(TableMeta.column_account_id)) ;
		accountBean.setUserId(rs.getLong(TableMeta.column_user_id)) ;
		accountBean.setAccount(rs.getString(TableMeta.column_mask_code)) ;
		accountBean.setPoint(rs.getInt(TableMeta.column_point)) ;
		accountBean.setUsedPoint(rs.getInt(TableMeta.column_point_used)) ;
		accountBean.setLastTime(rs.getLong(TableMeta.column_last_time)) ;
		accountBean.setBirthTime(rs.getLong(TableMeta.column_birth_time));
		accountBean.setStatus(rs.getInt(TableMeta.column_status));
		accountBean.setValidTime(rs.getLong(TableMeta.column_valid_time)) ;
		accountBean.setSendCount(rs.getInt(TableMeta.column_send_count)) ;
		accountBean.setReportCount(rs.getInt(TableMeta.column_report_count)) ;
		accountBean.setFirstTime(rs.getLong(TableMeta.column_first_time)) ;
		return accountBean;
	}
	
	public Long getAccountId() {
		return accountId;
	}
	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}
	/**
	 * 子账号格式是否合法
	 * 
	 * */
    public static boolean isValidFormat(String account)
    {
    	return account != null && account.matches("[0-9a-zA-Z_@|]{32,48}") ;
    }
    /**
     * 子账号是否有效:删除、过期的子账号为无效子账号，冻结的子账号属于有效账号
     * 
     * */
    public static boolean isValid(AccountBean account)
    {
    	return account!=null && !account.isTimeout() && !account.isDeleted() ;
    }
	public long getUserId() {
		return userId;
	}
	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public int getPoint() {
		return point.get();
	}
	public void setPoint(int point) {
		this.point.set(point);
		this.needSync.set(true);
	}
	public int getUsedPoint() {
		return usedPoint.get();
	}
	public void setUsedPoint(int usedPoint) {
		this.usedPoint.set(usedPoint);
		this.needSync.set(true) ;
	}
	
	/**
	 * 减少已用点数,同时增加报错提数
	 * 
	 * */
	public void decreaseUsedPoint(int point)
    {
		reportCount.incrementAndGet() ;
		reportCountIncrement.incrementAndGet() ;
		usedPoint.addAndGet(-point) ;
		usedPointIncrement.addAndGet(-point) ;
		needSync.set(true) ;
    }
	
	
	
	/**
	 * 增加已用点数,同时增加发送答题数
	 * 
	 * 
	 * */
	public void increaseUsedPoint(int point, boolean countFlag)
	{
		if(countFlag)
		{	
			sendCount.incrementAndGet() ;
			sendCountIncrement.incrementAndGet() ;
		}
		usedPoint.addAndGet(point) ;
		usedPointIncrement.addAndGet(point) ;
		needSync.set(true) ;
	}
	
	
    @Override
    public PreparedStatement getPreparedStatement(Connection conn)
            throws SQLException
    {
        String sql = " update " + TableMeta.table_account + " set " +
                        TableMeta.column_point_used + " = "+ TableMeta.column_point_used +" + ? ," +
                        TableMeta.column_send_count + " = "+ TableMeta.column_send_count +" + ? ," +
                        TableMeta.column_report_count + " = "+ TableMeta.column_report_count +" + ? ," +
                        TableMeta.column_last_time + " = ? ," +
                        TableMeta.column_valid_time + " = ? ," +
                        TableMeta.column_status + " = ? ," +
                        TableMeta.column_point + " = "+ TableMeta.column_point +" + ?, " +
                        TableMeta.column_first_time + " = ? " +
                        " where " + TableMeta.column_account_id + " = ? ";
       
        return conn.prepareStatement(sql);
    }
    
    /**
     * 是否过期账号
     * 
     * */
    public boolean isTimeout()
    {
    	return firstTime > 0 && System.currentTimeMillis() > validTime ;
    }
    
    public boolean isUsed()
    {
    	return firstTime > 0 ;
    }
    
    public void setUsed()
    {
    	if (firstTime <= 0)
    	{
    		firstTime = System.currentTimeMillis() ;
    		validTime = firstTime + validTime ;
    	}
    	needSync.set(true) ;
    }
    
    @Override
    public boolean needSynchronized()
    {
        return needSync.get();
    }
    
    @Override
    public boolean setParameters(PreparedStatement ps)
    {
        try
        {
            ps.setInt(1, usedPointIncrement.getAndSet(0)) ;
            ps.setInt(2, sendCountIncrement.getAndSet(0));
            ps.setInt(3, reportCountIncrement.getAndSet(0));
            ps.setLong(4, lastTime) ;
            ps.setLong(5, validTime) ;
            ps.setInt(6, status.get());
            ps.setInt(7,pointIncrement.getAndSet(0));
            ps.setLong(8, firstTime) ;
            ps.setLong(9, accountId) ;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            try 
            {
				ps.clearParameters() ;
			}
            catch (SQLException e1) 
            {
			}
            return false ;
        }
        // 重置
        needSync.set(false) ;
//        usedPointIncrement.set(0);
//        sendCountIncrement.set(0) ;
//        reportCountIncrement.set(0) ;
//        pointIncrement.set(0) ;
        return true;
    }
    
    public String getStatusDes()
    {
    	int curStatus = status.get() ;
    	if (curStatus == 0)
    		return "正常";
    	if (curStatus == -1)
    		return "已删除";
    	if (curStatus == 1)
    		return "已冻结";
    	return "未知状态" ;
    }
    public String toString()
    {
    	StringBuffer sb = new StringBuffer(128) ;
    	sb.append("账号:").append(this.account) ;
    	sb.append(",点数:").append(this.point).append(",已用点数:").append(this.usedPoint).append("\n") ;
    	sb.append("创建时间:").append(new Timestamp(this.birthTime)).append(",有效期:").append(new Timestamp(this.validTime)) ;
    	sb.append(",发送题数:").append(this.sendCount).append(",报错题数:").append(this.reportCount) ;
    	sb.append(",状态:").append(getStatusDes()) ;
    	return sb.toString() ;
    }
//    public String toJSON()
//    {
//    	StringBuffer result = new StringBuffer(512) ;
//    	result.append("validDate:")
//    	return result.toString() ;
//    }

    /**
     * 增加可用点数，用于充值
     * 
     * */
	public synchronized void increasePoint(int point) 
	{
		this.point.addAndGet(point) ;
		this.pointIncrement.addAndGet(point) ;
		needSync.set(true) ;
//		this.point += point ;
//		this.pointIncrement += point ;
//		needSync = true ;
	}

	public int getLeftPoint() 
	{
		return point.get()-usedPoint.get();
	}

	public long getLastTime() {
		return lastTime;
	}

	public void setLastTime(long lastTime) {
		this.lastTime = lastTime;
		needSync.set(true);
	}

	public long getBirthTime() {
		return birthTime;
	}

	public void setBirthTime(long birthTime) {
		this.birthTime = birthTime;
	}

	public int getStatus() {
		return status.get();
	}

	public void setStatus(int status) {
		this.status.set(status);
	}

	public long getValidTime() {
		return validTime;
	}

	public void setValidTime(long validTime) {
		this.validTime = validTime;
	}

	public int getSendCount() {
		return sendCount.get();
	}

	public void setSendCount(int sendCount) {
		this.sendCount.set(sendCount);
	}

	public int getReportCount() {
		return reportCount.get();
	}

	public void setReportCount(int reportCount) {
		this.reportCount.set(reportCount);
	}
	
	public void setDeleted()
	{
		this.status.set(-1) ;
		this.needSync.set(true);
	}

	public boolean isDeleted()
	{
		return this.status.get() == -1 ;
	}
	public void recharge(RechargeCardBean rechargeCard)
	{
		rechargeCard.setUsed(1) ;
    	increasePoint(rechargeCard.getPoint()) ;
    	if(rechargeCard.getValidTime() > validTime)
    		validTime = (rechargeCard.getValidTime()) ;
    	
	}
	/**
	 * 冻结账号
	 * 
	 * **/
	public void freeze()
	{
		this.status.set(1);
		needSync.set(true);
	}
	/**
	 * 解冻帐号
	 * 
	 * */
    public void unfreeze()
    {
    	this.status.set(0) ;
    	needSync.set(true) ;
    }
    /**
     * 账号是否被冻结
     * 
     * */
    public boolean isFreeze()
    {
    	return this.status.get() == 1 ;
    }

	public long getFirstTime() {
		return firstTime;
	}

	public void setFirstTime(long firstTime) {
		this.firstTime = firstTime;
	}

	public int getReportCountIncrement() {
		return reportCountIncrement.get();
	}

	/**
	 * 获取有效天数 
	 * 
	 * */

	public long getValidDate() 
	{
		return (this.validTime - startTime)/(24*60*60*1000) ;
	
	}
    
}
